import api from '@/pages/MerchantAccount/MerchantUser/UserManagement/request';
import { PlusOutlined } from '@ant-design/icons';
import { DrawerForm, ProFormSwitch, ProFormText } from '@ant-design/pro-components';
import { FormattedMessage } from '@umijs/max';
import { Button, Form } from 'antd';
import { useState } from 'react';

export type FormConfig = { Component: any; props: Record<string, any> };
export interface Props {
  isEdit?: boolean;
  data?: MerchantAccountUserManagementApi.ListResponse;
  onSuccess?: () => void;
  onCancel?: () => void;
}
function ShopUserManagementForm(props: Props) {
  const { data, isEdit = false } = props;

  const [form] = Form.useForm();
  const [formData, setFormData] = useState<any>({});
  const [info, setInfo] = useState<Partial<MerchantAccountUserManagementApi.InfoResponse>>({});

  const getInfo = async (params: MerchantAccountUserManagementApi.InfoParams) => {
    const info = await api.getInfo(params);
    setInfo(info);
    form.setFieldsValue(info);
    setFormData(info);
  };

  const onOpenChange = (open: boolean) => {
    if (open) {
      if (data && data.id) {
        getInfo({ id: data.id });
      }
    } else {
      setInfo({});
      form.resetFields();
      setFormData({});
      props.onCancel?.();
    }
  };
  const onSubmit = async () => {
    const { username, contactPhone, status, password } = formData;
    const { id = '' } = info;

    if (isEdit) {
      const params: MerchantAccountUserManagementApi.UpdateParams = {
        id,
        username,
        contactPhone,
        status,
        password: password || null,
      };
      const data = await api.update(params);
      if (data.success) props.onSuccess?.();
      return data.success;
    } else {
      const params: MerchantAccountUserManagementApi.CreateParams = {
        username,
        contactPhone,
        status,
      };
      const data = await api.create(params);
      if (data.success) props.onSuccess?.();
      return data.success;
    }
  };

  return (
    <DrawerForm
      autoFocusFirstInput
      title={`${isEdit ? '编辑' : '新建'}用户`}
      form={form}
      drawerProps={{ destroyOnClose: true }}
      resize={{
        maxWidth: window.innerWidth * 0.8,
        minWidth: 400,
        onResize() {},
      }}
      trigger={
        isEdit ? (
          <Button type="link">编辑</Button>
        ) : !!data ? (
          <PlusOutlined />
        ) : (
          <Button type="primary">
            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
          </Button>
        )
      }
      onOpenChange={onOpenChange}
      onFinish={onSubmit}
    >
      <ProFormText
        required
        name="username"
        label="用户名"
        placeholder="请输入用户名"
        rules={[{ required: true }]}
        fieldProps={{
          value: formData.username,
          onChange: (e) => setFormData({ ...formData, username: e.target.value }),
        }}
      />

      <ProFormText
        required
        name="contactPhone"
        label="手机号"
        placeholder="请输入手机号"
        rules={[{ required: true }, { pattern: /^1\d{10}/, message: '请输入正确的手机号' }]}
        fieldProps={{
          value: formData.contactPhone,
          onChange: (e) => setFormData({ ...formData, contactPhone: e.target.value }),
        }}
      />
      {isEdit && (
        <ProFormText.Password
          name="password"
          label="密码"
          placeholder="请输入密码"
          fieldProps={{
            value: formData.password,
            onChange: (e) => setFormData({ ...formData, password: e.target.value }),
          }}
        />
      )}
      <ProFormSwitch
        required
        name="status"
        label="状态"
        placeholder="请选择状态"
        checkedChildren="启用"
        unCheckedChildren="禁用"
        rules={[{ required: true }]}
        fieldProps={{
          checked: !!formData.status,
          onChange: (value) => {
            setFormData({ ...formData, status: value ? 1 : 0 });
          },
        }}
      />
    </DrawerForm>
  );
}

export default ShopUserManagementForm;
